package com.project.school_flate.serviceimpl.com;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.google.gson.Gson;
import com.kuaidi100.sdk.api.BOrderOfficial;
import com.kuaidi100.sdk.api.QueryTrack;
import com.kuaidi100.sdk.core.IBaseClient;
import com.kuaidi100.sdk.pojo.HttpResult;
import com.kuaidi100.sdk.request.BOrderReq;
import com.kuaidi100.sdk.request.PrintReq;
import com.kuaidi100.sdk.request.QueryTrackParam;
import com.kuaidi100.sdk.request.QueryTrackReq;
import com.kuaidi100.sdk.utils.SignUtils;
import com.project.school_flate.service.com.KuaiDi100Service;
import com.project.school_flate.util.Result.Result;
import com.project.school_flate.util.kuidi100.ExpressShipment;
import com.project.school_flate.util.kuidi100.SelectKuaiDi;
import com.project.school_flate.util.system.ComVariableUtil;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;
@Service(value = "kuaiDi100ServiceImpl")
public class KuaiDi100ServiceImpl implements KuaiDi100Service {

    @Resource
    private RedisTemplate redisTemplate;

    /**
     * 智能识别接口
     * NUM =单号
     * KEY =授权码
     */
    private static final String AUTONUMBER_AUTO_URL = "http://www.kuaidi100.com/autonumber/auto?num=NUM&key=KEY";
    /**
     * 快递100查询快递请求接口（post）
     */
    private static final String POLL_QUERY_URL = "https://poll.kuaidi100.com/poll/query.do";
    /**
     * 快递公司寄件接口（post）
     */
    //private static final String EXPRESS_SHIPMENT_URL = "https://poll.kuaidi100.com/order/borderapi.do";
    private static final String EXPRESS_SHIPMENT_URL = "https://api.kuaidi100.com/apiMock/border";//沙箱地址


    /**
     * 商家寄件下单
     * @throws Exception
     */
    @Override
    public Result testBorderOfficial(ExpressShipment expressShipment) throws Exception {
        PrintReq printReq = new PrintReq();
        BOrderReq bOrderReq = new BOrderReq();
        bOrderReq.setKuaidicom(expressShipment.getKuaidicom());
        bOrderReq.setSendManName(expressShipment.getSendManName());
        bOrderReq.setSendManMobile(expressShipment.getSendManMobile());
        bOrderReq.setSendManPrintAddr(expressShipment.getSendManPrintAddr());
        bOrderReq.setRecManName(expressShipment.getRecManName());
        bOrderReq.setRecManMobile(expressShipment.getRecManMobile());
        bOrderReq.setRecManPrintAddr(expressShipment.getRecManPrintAddr());
        bOrderReq.setCallBackUrl(ComVariableUtil.getSystemValue("collPath") + "/kuaidi100/rollbackKuaiDi100?deliveryRecordId="  + expressShipment.getOrderId());
        String t = String.valueOf(System.currentTimeMillis());
        String param = new Gson().toJson(bOrderReq);
        printReq.setKey(ComVariableUtil.getSystemValue("kd100_key"));
        printReq.setSign(SignUtils.printSign(param,t, ComVariableUtil.getSystemValue("kd100_key"), ComVariableUtil.getSystemValue("kd100_secret")));
        printReq.setT(t);
        printReq.setParam(param);
        //printReq.setMethod(ApiInfoConstant.B_ORDER_OFFICIAL_ORDER_METHOD);
        printReq.setMethod("https://api.kuaidi100.com/apiMock/border");
        IBaseClient bOrder = new BOrderOfficial();
        return Result.ok(bOrder.execute(printReq));
    }

    /**
     * 实时快递查询
     * @throws Exception
     */
    @Override
    public Result testQueryTrack(SelectKuaiDi selectKuaiDi) throws Exception{
        //先查询该单号是否在缓存中存在
        boolean exists = redisTemplate.hasKey(selectKuaiDi.getCom() + "_" + selectKuaiDi.getNum());
        if(exists){
            //如果存在，直接返回
            Long size = redisTemplate.boundListOps(selectKuaiDi.getCom() + "_" + selectKuaiDi.getNum()).size();
            List<JSONObject> list = redisTemplate.boundListOps(selectKuaiDi.getCom() + "_" + selectKuaiDi.getNum()).range(0, size);
            return Result.ok(list);
        }
        QueryTrackReq queryTrackReq = new QueryTrackReq();
        QueryTrackParam queryTrackParam = new QueryTrackParam();
        queryTrackParam.setCom(selectKuaiDi.getCom());
        queryTrackParam.setNum(selectKuaiDi.getNum());
        queryTrackParam.setPhone(selectKuaiDi.getPhone());
        String param = new Gson().toJson(queryTrackParam);
        queryTrackReq.setParam(param);
        queryTrackReq.setCustomer(ComVariableUtil.getSystemValue("kd100_customer"));
        queryTrackReq.setSign(SignUtils.querySign(param , ComVariableUtil.getSystemValue("kd100_key"), ComVariableUtil.getSystemValue("kd100_customer")));
        IBaseClient baseClient = new QueryTrack();
        HttpResult httpResult = baseClient.execute(queryTrackReq);
        String json = httpResult.getBody();
        try {
            JSONObject jsonObject = JSONObject.parseObject(json);
            JSONArray data = jsonObject.getJSONArray("data");
            String js = JSONObject.toJSONString(data, SerializerFeature.WriteClassName);
            List<JSONObject> list = JSONObject.parseArray(js, JSONObject.class);
            for(JSONObject jSONObject : list){
                redisTemplate.boundListOps(selectKuaiDi.getCom() + "_" + selectKuaiDi.getNum()).rightPush(jSONObject);
                redisTemplate.expire(selectKuaiDi.getCom() + "_" + selectKuaiDi.getNum(),35, TimeUnit.MINUTES);
            }
            return Result.ok(jsonObject.get("data"));
        }catch (Exception e){
            return Result.ok(json);
        }
    }
}
